package com.aiden.app.common.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import com.aiden.app.common.R
import com.aiden.app.common.extension.sp2px

/**
 * 字母索引栏
 *
 * @author yanggeng
 * @date 2019/2/12 下午2:21
 */
class IndexBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttrs: Int = 0) : View(context, attrs, defStyleAttrs) {

    private val DEFAULT_INDEX_ITEMS = arrayListOf("#", "A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")
    private var textSize: Int = 0
    private var normalTextColor: Int = 0
    private var selectedTextColor: Int = 0
    private var selectedBackgroundColor: Int = 0
    private var paint: Paint = Paint()
    private var selectedPaint: Paint = Paint()
    private var selectedBgPaint = Paint()
    private var mWidth: Int = 0
    private var mHeight: Int = 0
    private var mIsUseScreenHeight: Boolean = true
    private var mTopMargin = 0f //居中绘制，文字绘制起点和控件顶部的间隔
    private var mItemHeight = 0f // 每个item的高度
    private var mCurrentIndex = -1
    private var navigationBarHeight = 0
    private var onIndexTouchedChangedListener: OnIndexTouchedChangedListener? = null
    private var mOverlayTextView: TextView? = null
    private var mIndexItems: MutableList<String> = mutableListOf()

    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.IndexBar)
        textSize = a.getDimensionPixelSize(R.styleable.IndexBar_ib_textSize, context.sp2px(14))
        normalTextColor = a.getColor(R.styleable.IndexBar_ib_normalTextColor, context.resources.getColor(R.color.color_gray_ae))
        selectedTextColor = a.getColor(R.styleable.IndexBar_ib_selectedTextColor, context.resources.getColor(R.color.color_white))
        selectedBackgroundColor = a.getColor(R.styleable.IndexBar_ib_selectedBackground, context.resources.getColor(R.color.color_blue_2dbefe))
        mIsUseScreenHeight = a.getBoolean(R.styleable.IndexBar_ib_isUseScreenHeight, mIsUseScreenHeight)
        paint.textSize = textSize.toFloat()
        paint.color = normalTextColor

        selectedPaint.textSize = textSize.toFloat()
        selectedPaint.color = selectedTextColor
        selectedBgPaint.color = selectedBackgroundColor
        a.recycle()
        if (mIndexItems.size == 0) {
            mIndexItems.addAll(DEFAULT_INDEX_ITEMS)
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        var index = ""
        for (i in 0 until mIndexItems.size) {
            index = mIndexItems[i]
            val fm = paint.fontMetrics
            if (i == mCurrentIndex) {
                canvas?.drawCircle(mWidth.toFloat() / 2, mTopMargin + mItemHeight * i + mItemHeight / 2, mWidth.toFloat() / 2, selectedBgPaint)
            }
            canvas?.drawText(index, (mWidth - paint.measureText(index)) / 2, mItemHeight / 2 + (fm.bottom - fm.top) / 2 - fm.bottom + mItemHeight * i + mTopMargin,
                    if (i == mCurrentIndex) selectedPaint else paint)

        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mWidth = width
        if(mIsUseScreenHeight){
        if (Math.abs(h - oldh) == navigationBarHeight) {
            // 底部导航栏隐藏或显示
            mHeight = h
        } else {
            // 避免软键盘弹出时挤压
            mHeight = Math.max(height, oldh)
        }}else{
            mHeight = height
        }
        mItemHeight = mHeight / mIndexItems.size.toFloat()
        mTopMargin = (mHeight - mItemHeight * mIndexItems.size) / 2
    }

    override fun performClick(): Boolean {
        return super.performClick()
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        performClick()
        when (event?.action!!) {
            MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
                val y = event.y
                val indexSize = mIndexItems.size
                var touchIndex = (y / mItemHeight).toInt()
                if (touchIndex < 0) {
                    touchIndex = 0
                } else if (touchIndex >= indexSize) {
                    touchIndex = indexSize - 1
                }
                if (onIndexTouchedChangedListener != null) {
                    if (touchIndex != mCurrentIndex) {
                        mCurrentIndex = touchIndex
                        if (mOverlayTextView != null) {
                            mOverlayTextView?.visibility = View.VISIBLE
                            mOverlayTextView?.text = mIndexItems[touchIndex]
                        }
                        onIndexTouchedChangedListener?.onIndexChange(mIndexItems[touchIndex], touchIndex)
                        invalidate()
                    }
                }
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
//                mCurrentIndex = -1
                if (mOverlayTextView != null) {
                    mOverlayTextView?.visibility = View.GONE
                }
                invalidate()
            }
        }
        return true
    }

    fun setIndexData(indexData: List<String>) {
        this.mIndexItems.clear()
        this.mIndexItems.addAll(indexData)
        invalidate()
    }

    fun setCurrentItem(item: String) {
        this.mCurrentIndex = mIndexItems.indexOf(item)
        invalidate()
    }

    fun setNavigationBarHeight(height: Int) {
        navigationBarHeight = height
    }

    fun setOverlayTextView(overlay: TextView) {
        this.mOverlayTextView = overlay
    }

    fun setOnIndexTouchedCHangedListener(onIndexTouchedChangedListener: OnIndexTouchedChangedListener) {
        this.onIndexTouchedChangedListener = onIndexTouchedChangedListener
    }

    interface OnIndexTouchedChangedListener {
        fun onIndexChange(index: String, position: Int)
    }
}